package com.woniuxy.controller;

import com.woniuxy.ResponseResult;
import com.woniuxy.ServerResponse;
import com.woniuxy.exception.EmailExistException;
import org.springframework.dao.DataAccessException;
import org.springframework.expression.AccessException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xxhcm on 2021/3/24.
 */
@Controller
@RestControllerAdvice
public class ExceptionController {
    @ExceptionHandler({DataAccessException.class})
    public ServerResponse<Void> exception(DataAccessException e){
        e.printStackTrace();
        return ServerResponse.createByDataAccessErrorCodeMessage("数据访问错误");

    }

    @ExceptionHandler(IOException.class)
    public ServerResponse<Void> hand(DataAccessException e){
        e.printStackTrace();
        return ServerResponse.createByErrorCodeMessage(44,"wangluocuowu");
    }
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ServerResponse<Map<String,String>> exceptions(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult result =e.getBindingResult();
        if (result.hasErrors()) {

            List<FieldError> fieldErrors = result.getFieldErrors();
            Map<String,String> map = new HashMap<>();
            fieldErrors.forEach(c->map.put(c.getField(),c.getDefaultMessage()));

            return ServerResponse.createByError(map);
        }
        return null;
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public ServerResponse<Map<String,String>> exceptionss(ConstraintViolationException e){

        return ServerResponse.createByErrorCodeMessage(333,e.getMessage());
    }
    @ExceptionHandler(EmailExistException.class)
    public ServerResponse<Void> EmailExsit(EmailExistException e){
        return ServerResponse.createByErrorCodeMessage(333,e.getMessage());
    }




}
